package tiptop.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.SecureRandom;
import java.util.UUID;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;

public class AESUtil {
	
	public static String password = Md5Utils.stringMD5("tiptop");
	
	/**
	 * 加密
	 * 
	 * @param content
	 *            需要加密的内容
	 * @param password
	 *            加密密码
	 * @return
	 */
	public static byte[] encrypt(byte[] byteContent, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			//byte[] byteContent = content.getBytes("utf-8");
			cipher.init(Cipher.ENCRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(byteContent);
			return result; // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	/**
	 * 解密
	 * 
	 * @param content
	 *            待解密内容
	 * @param password
	 *            解密密钥
	 * @return
	 */
	public static byte[] decrypt(byte[] content, String password) {
		try {
			KeyGenerator kgen = KeyGenerator.getInstance("AES");
			kgen.init(128, new SecureRandom(password.getBytes()));
			SecretKey secretKey = kgen.generateKey();
			byte[] enCodeFormat = secretKey.getEncoded();
			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			byte[] result = cipher.doFinal(content);
			return result; // 加密
		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 文件加密
	 * @param filePath 文件
	 * @param keyLength 校验码长度
	 * @return
	 */
	public static boolean encryptFile(String filePath) {
	    try {
	    	//检测需要加密文件
	    	File file = new File(filePath);
			String path = file.getPath();
			if (!file.exists()) {
				return false;
			}
			//生成文件校验信息
			String fileMD5 = Md5Utils.fileMD5(filePath);

//			KeyGenerator kgen = KeyGenerator.getInstance("AES");
//			kgen.init(128, new SecureRandom(password.getBytes()));
//			SecretKey secretKey = kgen.generateKey();
//			byte[] enCodeFormat = secretKey.getEncoded();
//			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
//			Cipher cipher = Cipher.getInstance("AES");// 创建密码器
//			cipher.init(Cipher.ENCRYPT_MODE, key);
			
			//初始化文件
			int index = path.lastIndexOf("\\");
			String destFile = path.substring(0, index) + File.separatorChar + UUID.randomUUID().toString();
			File dest = new File(destFile);
			InputStream in = new FileInputStream(filePath);
			OutputStream out = new FileOutputStream(destFile);
			
			byte[] buffer = new byte[in.available()];
			int r;
			byte[] buffer2 = new byte[in.available()];
			while ((r = in.read(buffer)) > 0) {
				//buffer2 = cipher.doFinal(buffer);
				buffer2 = encrypt(buffer,password);
				out.write(buffer2);
				out.flush();
			}
			in.close();
			out.close();
			file.delete();
			dest.renameTo(new File(filePath));
			return true;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return false;
	    }
	}
	
	/**
	 * 解密文件
	 * @param filePath
	 * @return
	 */
	public static boolean decryptFile(String filePath) {
	    try {
	    	//检测需要解密文件
	    	File file = new File(filePath);
	    	String path = file.getPath();
			if (!file.exists()) {
				return false;
			}

//			KeyGenerator kgen = KeyGenerator.getInstance("AES");
//			kgen.init(128, new SecureRandom(password.getBytes()));
//			SecretKey secretKey = kgen.generateKey();
//			byte[] enCodeFormat = secretKey.getEncoded();
//			SecretKeySpec key = new SecretKeySpec(enCodeFormat, "AES");
//			Cipher cipher = Cipher.getInstance("AES/ECB/NoPadding");// 创建密码器
//			cipher.init(Cipher.DECRYPT_MODE, key);// 初始化
			
			//初始化文件
			int index = path.lastIndexOf("\\");
			String destFile = path.substring(0, index) + File.separatorChar + UUID.randomUUID().toString();
			File dest = new File(destFile);
			if (!dest.getParentFile().exists()) {
				dest.getParentFile().mkdirs();
			}

			InputStream in = new FileInputStream(filePath);
			OutputStream out = new FileOutputStream(destFile);
			byte[] buffer = new byte[in.available()];
			byte[] buffer2 = new byte[in.available()];
			int r;
			//分段加密文件
			while ((r = in.read(buffer)) > 0) {
				//buffer2 = cipher.doFinal(buffer);
				buffer2 = decrypt(buffer,password);
				out.write(buffer2);
				out.flush();
			}
			in.close();
			out.close();
			file.delete();
			dest.renameTo(new File(filePath));
			return true;
	    } catch (Exception e) {
	        e.printStackTrace();
	        return false;
	    }
	}
	
	public static void main(String[] args) { 
		System.out.println(encryptFile("D:\\DocAudit.xlsx"));
		System.out.println(decryptFile("D:\\DocAudit.xlsx"));
	}
}
